package com.wedjg.concurrency.example.singleton;

import com.wedjg.concurrency.annotations.ThreadSafe;

/**
 * 懒汉式单例
 * 安全发布对象
 * 在Example4的基础上加上volatile来禁止重排序
 * volatile + 双重检测机制来确保线程安全
 *
 * @author wedjg
 * @version 1.0
 * @date 2019/6/2
 */
@ThreadSafe
public class SingletonExample5 {

    private volatile static SingletonExample5 instance = null;

    private SingletonExample5() {
    }

    public static SingletonExample5 getInstance() {
        // 双重检测机制
        if (instance == null) {
            synchronized (SingletonExample5.class) {
                if (instance == null) {
                    instance = new SingletonExample5();
                }
            }

        }
        return instance;
    }
}
